using SqlSugar;
using IM.Easy.Core.Services;
using IM.Easy.Core.Utils;
using IM.Easy.Infrastructure.Query;
using IM.Easy.Core.Extensions;
using IM.Easy.Entity.System;
using IM.Easy.SystemServices.Dtos;
using IM.Easy.SystemServices.IServices;

namespace IM.Easy.SystemServices.Services
{
    public class RoleMenuService : AppServices, IRoleMenuService
    {

        public RoleMenuService(ISqlSugarClient db) : base(db)
        {

        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="roleId"></param>
        /// <param name="menuIds"></param>
        /// <returns></returns>
        public bool Save(long roleId, long[] menuIds)
        {
            var role = Db.Queryable<SysRole>().Single(s => s.Id == roleId);
            role.RoleMenus = menuIds.Select(menuId => new SysRoleMenu { RoleId = roleId, MenuId = menuId }).ToList();

            var result = Db.UpdateNav(role, new UpdateNavRootOptions
            {
                IsInsertRoot = false
            })
              .Include(x => x.RoleMenus)
               .ExecuteCommand();
            return result;
        }

        /// <summary>
        /// 获取菜单
        /// </summary>
        /// <param name="roldId"></param>
        /// <returns></returns>
        public List<SysMenu> GetMenus(long roldId)
        {
            var menus = Db.Queryable<SysMenu>()
                          .InnerJoin<SysRoleMenu>((m, rm) => m.Id == rm.MenuId)
                          .Where((m, rm) => rm.RoleId == roldId)
                          .Select((m, rm) => m)
                          .ToList();
            return menus;
        }

        /// <summary>
        /// 通过获取多角色菜单
        /// </summary>
        /// <param name="roleIds"></param>
        /// <returns></returns>
        public List<SysMenu> GetMenus(params long[] roleIds)
        {
            var menus = Db.Queryable<SysMenu>()
                        .InnerJoin<SysRoleMenu>((m, rm) => m.Id == rm.MenuId)
                        .Where((m, rm) => roleIds.Contains(rm.RoleId))
                        .Select((m, rm) => m)
                        .ToList();
            return menus;
        }

        /// <summary>
        /// 通过角色标识获取菜单
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public List<SysMenu> GetMenus(string roleKey)
        {
            var menus = Db.Queryable<SysMenu>()
                      .InnerJoin<SysRoleMenu>((m, rm) => m.Id == rm.MenuId)
                      .InnerJoin<SysRole>((m, rm, r) => rm.RoleId == r.Id)
                      .Where((m, rm, r) => r.Code == roleKey)
                      .Select((m, rm) => m)
                      .ToList();
            return menus;
        }
    }
}
